package com.cn.ccp.action.system;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

import jxl.Sheet;
import jxl.Workbook;

import org.apache.log4j.Logger;

import com.cn.ccp.action.BaseAction;
import com.cn.ccp.bean.FacultyBean;
import com.cn.ccp.bean.FilePathBean;
import com.cn.ccp.bean.ResourseBean;
import com.cn.ccp.bean.SpecialtyBean;
import com.cn.ccp.bean.TeachingGroupBean;
import com.cn.ccp.bean.UserBean;
import com.cn.ccp.util.CCPContants;
import com.cn.ccp.util.Contants;


public class TeacherAction extends BaseAction {
	private Logger log = Logger.getLogger(TeacherAction.class);
	private UserBean userBean ;
	private List<UserBean> userList ;
	private List<String> specialtyList ;
	private SelectItem[] teacherTypeSelectItem ;
	private SelectItem[] facultySelectItem ;
	private SelectItem[] specialtySelectItem ;
	private SelectItem[] teachGroupSelectItem ;//教研组下拉框
	private SelectItem[] positionalSelectItem ;//职称下拉框
	
	private List<String> specialtyListBak ; 
	private String facultyIDBack = "" ;
	
	//查询字段
	private String number ;
	private String searchUserType ;
	private String searchStatus ;
	private String searchUserName ;
	private String searchFacultyId ;
	private String searchSpecialtyId;
	private List<String> teachGropList;//教研组id
	
	
	public void imageClick(){
//		System.out.println();
	}
	
	public String edit(){
		if(userBean.getUserName().equals("")){
			showMsg("userName", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getLogin_name().equals("")){
			showMsg("loginuserName", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		
		boolean checkStatus = getUserService().checkLoginUserNameIsOn(userBean.getId(), userBean.getLogin_name());
		if(checkStatus){
			showMsg("loginuserName", "user_page_label_login_username_error_1");
			return "";
		}
		
		if(userBean.getPassword().equals("")){
			showMsg("password", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		boolean passwordISChange  = false ;
		if(userBean.getId() > 0 ){
			passwordISChange = getTeacherService().checkPasswrodIsChange(userBean.getId(), userBean.getPassword());
			if(passwordISChange){
				if(!userBean.getPassword().equals(userBean.getShowPassword())){
					showMsg("passwordok", "user_page_label_error_2");
					return "";
				}
			}
		}
		
		
		if(userBean.getDormitoryAddress().equals("")){
			showMsg("dormitoryAddress", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getEmail().equals("")){
			showMsg("email", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getMobile().equals("")){
			showMsg("mobile", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getHomeAddress().equals("")){
			showMsg("homeAddress", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getBirtdate().equals("")){
			showMsg("birtdate", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getAdmissionTime().equals("")){
			showMsg("admissionTime", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getZipCode().equals("")){
			showMsg("zipCode", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
		if(userBean.getFacultyId().equals("-1")){
			showMsg("facultyid", "javax.faces.component.UIInput.REQUIRED");
			return "";
		}
//		if(userBean.getSpecialtyId().equals("-1")){
//			showMsg("specialty", getMessages("javax.faces.component.UIInput.REQUIRED"));
//			return "";
//		}
//		if(userBean.getGrade().equals("-1")){
//			showMsg("grade", getMessages("user_page_label_grade_no_select"));
//			return "";
//		}
		if(userBean.getImage() == null || userBean.getImage().equals("")){
			//showMsg("image", getMessages("user_page_label_add_image_upload"));
//			userBean.setImage("images/book-default.png");
			//return "";
		}
		if(userBean.getUserType() == null || "-1".equalsIgnoreCase(userBean.getUserType())){
			userBean.setUserType("2");
		}
		for(String id:teachGropList)
			log.info("--------"+id);
//		return MAIN;
		String flag = "" ;
		if(userBean.getId() == 0)
			flag = save();
		else
			flag = update(passwordISChange);
		
		userBean = new UserBean();
		
		return flag ;
	}
	
	public String editStudent(){
		userBean.setUserType("1");
		return edit();
	}
	
	public String editTeacher(){
		return edit();
	}
	
	public String save(){
		int  userId = getTeacherService().sava(userBean,teachGropList);
		FilePathBean filePathBean = getFilePathService().getFlagBean();
		String imgFile = filePathBean.getPath()+userBean.getImage();
		File file = new File(imgFile);
		String newPath = filePathBean.getPath()+userId+ File.separator + file.getName();
		File newDerect = new File(filePathBean.getPath()+userId+ File.separator);
		newDerect.mkdirs();
		try {
			new File(newPath).createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		CCPContants.copyFile(imgFile, newPath);
		userBean.setId(userId);
		userBean.setImage(userId +"/" + file.getName());
		getStudentService().update(userBean ,false);
		file.delete(); 
		CCPContants.getFilePath(userBean.getImage() , getFilePathService(),filePathBean.getId() , userBean.getId());
		getpagedetail();
		return MAIN;
	}
	
	public String update(boolean passwordISChange){
		try {
			String imgFile = getFilePathService().getFlagBean().getPath()+userBean.getImage();
			File file = new File(imgFile);
			if(!file.exists()){
				UserBean tub = getUserService().findById(userBean.getId());
				userBean.setImage(tub.getImage());
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		boolean flag = getTeacherService().update(userBean,teachGropList ,passwordISChange);
		if(flag){
			getpagedetail();
			return MAIN;
		}
		return "";
	}
	
	public void disableUser(){
		log.info("disable uses--------");
		for(UserBean u : userList){
			log.info(u);
			if(u.isDisable())
				getTeacherService().delete(u.getId());
		}
		getpagedetail();
	}
	
    private boolean selectAll; 
	public String disAndselectAll() {  
        for (UserBean user : userList) {  
        	if(user.getId() != 1)
        		user.setDisable(selectAll);  
        } 
        return "";
    }  

	public boolean isSelectAll() {
		return selectAll;
	}

	public void setSelectAll(boolean selectAll) {
		this.selectAll = selectAll;
	}

	public void delete(){
		try {
			FacesContext context = FacesContext.getCurrentInstance();// 取得上下文
			String id = (String)context.getExternalContext().getRequestParameterMap().get("id");// 得到页面的参数
			log.info("-------------delete()---------id = "+id);
			if(id == null || id.equals("null") || id.equals(""))
				return ;
			if(id.equals("1") ){
				return ;
			}
			getTeacherService().delete(Integer.parseInt(id));
			getpagedetail();
		} catch (Exception e) {
		}
	}
	
	
	public String goAdd(){
		log.info("--------------goAdd()------------------");
		userBean = null;
		userList = null ;
		specialtyList = null ;
		facultySelectItem = null ;
		specialtySelectItem = null ;
		specialtyList = null ;
		teachGropList = new ArrayList();
		return ADD;
	}
	
	/**
	 * 进入批量导入页面
	 * @return
	 */
	public String goInport(){
		log.info("--------------goInport()------------------");
		userBean = null;
		userList = null ;
		specialtyList = null ;
		facultySelectItem = null ;
		specialtySelectItem = null ;
		specialtyList = null ;
		teachGropList = new ArrayList();
		return "inportteacher";
	}
	
	public String doInportTeacher(){
		log.info("--------doInportTeacher()-----------");
		//TODO 2013-11-15 将学院字段数据写入excel中
//		if(userBean.getFacultyId().equals("-1")){
//			showMsg("faculty", "user_page_label_faculty_no_select");
//			return "";
//		}
		
		String savePath = CCPContants.SYS_PATH+"files"+File.separator + "teachers" + File.separator + CCPContants.getUserBean().getId() + File.separator;
		File[] f1 = new File(savePath).listFiles();
		if(f1 == null || f1.length <= 0){
			showMsg("uploadStudent", "user_page_label_upload_student_null_error");
			return "";
		}
		for(File f:f1)
			importFileForTeacher(f);
		getpagedetail();
		return MAIN;
	}
	
	private void importFileForTeacher(File file){
		Sheet sheet;
        Workbook book;
        try{
        	book = Workbook.getWorkbook(file); 
        	sheet = book.getSheet(0);
        	//从第五行开始读取数据，前面四行预留
        	int allLines = sheet.getRows();
        	log.info("-----------------allLines = "+allLines);
        	Map<String, Integer> facultyNameIdMap = new HashMap<String, Integer>();
        	Map<String, Integer> teacherGroupIdMap = new HashMap<String, Integer>();
        	for(int i=4;i<allLines;i++){
        		UserBean user = new UserBean();
        		user.setUserName(sheet.getCell(0, i).getContents());
        		user.setLogin_name(sheet.getCell(1, i).getContents());
        		user.setPassword(sheet.getCell(2, i).getContents());
        		user.setDormitoryAddress(sheet.getCell(3, i).getContents());
        		user.setEmail(sheet.getCell(4, i).getContents());
        		user.setSex(sheet.getCell(5, i).getContents());
        		user.setMobile(sheet.getCell(6, i).getContents());
        		user.setUserType(sheet.getCell(7, i).getContents());
        		user.setHomeAddress(sheet.getCell(8, i).getContents());
        		user.setBirtdate(sheet.getCell(9, i).getContents());
        		user.setZipCode(sheet.getCell(10, i).getContents());
        		user.setAdmissionTime(sheet.getCell(11, i).getContents());
        		user.setPositional(sheet.getCell(12, i).getContents());
        		user.setDescript(sheet.getCell(13, i).getContents());
        		String facultyName = sheet.getCell(14, i).getContents().trim().trim();
        		if(facultyNameIdMap.containsKey(facultyName)){
        			user.setFacultyId(""+facultyNameIdMap.get(facultyName)) ;
        		}else{
        			int id = getFacultyService().getFacultyIdByfacultyName(facultyName.trim());
        			user.setFacultyId(""+id) ;
        			facultyNameIdMap.put(facultyName, id);
        		}
        		String teacherGroups = sheet.getCell(15, i).getContents() ;
        		teacherGroups = teacherGroups.replace("，", ",").trim();
        		String[] strs = teacherGroups.split(",");
        		teachGropList.clear();
        		for(String s : strs)
        			if(s != null  && !s.equals("")){
        				if(teacherGroupIdMap.containsKey(s)){
        					teachGropList.add(""+teacherGroupIdMap.get(s.trim()));
        				}else{
        					int id = getTeachingGroupService().showBeanByName(s.trim()); 
        					teachGropList.add(""+id);
        					teacherGroupIdMap.put(s, id);
        				}
        			}
        		log.info(user);
        		getTeacherService().sava(user,teachGropList);
        	}
        	
        }catch(Exception e){
        	log.error("read file failed : ",e);
        	file.delete();
        }
	}
	
	
	
	public String showBean(){
		FacesContext context = FacesContext.getCurrentInstance();// 取得上下文
		String id = (String)context.getExternalContext().getRequestParameterMap().get("id");
		if(id == null || id.equals("null") || id.equals(""))
			return MAIN;
		if(id.equals("1") && !CCPContants.getUserBean().getUserName().equalsIgnoreCase("admin")){
			return "";
		}
		userBean = (UserBean) getTeacherService().findById(Integer.parseInt(id));
		if(userBean.getFacultyId() != null  && !userBean.getFacultyId().equals("") && !userBean.getFacultyId().equals("-1") ){
			List<SpecialtyBean> list = getSpecialtyService().getSpecialtyByFacultyId(Integer.parseInt(userBean.getFacultyId()));
			if(list != null){
				specialtySelectItem = new SelectItem[list.size()];
				for (int i = 0; i <list.size(); i++) 
					specialtySelectItem[i]  = new SelectItem(""+list.get(i).getId() , list.get(i).getSpecialtyname());
			}
		}
		
		List<TeachingGroupBean> tgList = getTeachingGroupService().getTeachingGroupListByUId(id);
		
		teachGropList = new ArrayList<String>();
		for(TeachingGroupBean bean : tgList)
			teachGropList.add(""+bean.getId());
		
		
		List<TeachingGroupBean> teList = getTeachingGroupService().getTeachingGroupListByFId(userBean.getFacultyId());
		if(teList != null){
			teachGroupSelectItem = new SelectItem[teList.size()];
			for(int i=0; i<teList.size();i++){
				teachGroupSelectItem[i] = new SelectItem(""+teList.get(i).getId() , teList.get(i).getTeaching_group_name());
			}
		}
		if(userBean.getImage() != null && !"".equalsIgnoreCase(userBean.getImage().trim())){
			String filePaht = CCPContants.getFilePath(userBean.getImage() , getFilePathService(),userBean.getFile_path_id() ,CCPContants.getUserBean().getId() );
			File file = new File(filePaht);
			userBean.setImage(CCPContants.getCurrUserId()+"/"+file.getName());
		}
		return UPDATE ;
	}
	
	
	public void search(){
		this.getpagedetail();
	}
	
	public void facultyChange(ValueChangeEvent  e){
		String facultyId = (String) e.getNewValue();
		log.info("------------facultyId = "+facultyId);
		if(facultyId != null  && !"".equalsIgnoreCase(facultyId.trim()) ){
			List<SpecialtyBean> list = getSpecialtyService().getSpecialtyByFacultyId(Integer.parseInt(facultyId));
			if(list != null){
				specialtySelectItem = new SelectItem[list.size()];
				for (int i = 0; i <list.size(); i++) 
					specialtySelectItem[i]  = new SelectItem(""+list.get(i).getId() , list.get(i).getSpecialtyname());
			}
			List<TeachingGroupBean> teList = getTeachingGroupService().getTeachingGroupListByFId(facultyId);
			if(teList != null){
				teachGroupSelectItem = new SelectItem[teList.size()];
				for(int i=0; i<teList.size();i++){
					teachGroupSelectItem[i] = new SelectItem(""+teList.get(i).getId() , teList.get(i).getTeaching_group_name());
				}
			}
		}else{
			userBean.setSpecialtyId("-1");
			specialtySelectItem = new SelectItem[0];
			teachGroupSelectItem = new SelectItem[0];
		}
	}
	
	public void searchClear(){
		number = "";
		searchUserType = "-1" ;
		searchStatus = "-1" ;
		searchUserName = "" ;
		searchFacultyId = "-1" ;
		searchSpecialtyId = "-1";
		specialtySelectItem = null ;
		specialtyList = null ;
	}
	
	
	
	public void approvalAuthority(){
		FacesContext context = FacesContext.getCurrentInstance();// 取得上下文
		String id = (String)context.getExternalContext().getRequestParameterMap().get("id");
		getTeacherService().approvalAuthority(id, "1");
		getpagedetail();
	}
	
	public void cancelApprovalAuthority(){
		FacesContext context = FacesContext.getCurrentInstance();// 取得上下文
		String id = (String)context.getExternalContext().getRequestParameterMap().get("id");
		getTeacherService().approvalAuthority(id, "0");
		getpagedetail();
	}
	
	@Override
	public void getpagedetail() {
		setItemCount(getTeacherService().getCount(number, searchUserType, searchStatus, searchUserName, searchFacultyId, searchSpecialtyId));
		int currentpage = getCurrentPage();
		int pagesize = getPageSize();
		int start = (currentpage - 1) * pagesize;
		if(start < 0)
			start = 0 ;
		userList = getTeacherService().pageQuery(start, pagesize, number, searchUserType, searchStatus, searchUserName, searchFacultyId, searchSpecialtyId);
	}
	
	public UserBean getUserBean() {
		@SuppressWarnings("unchecked")
		Map<String, String> varMap = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
		String fileName = varMap.get("fileName");
		String errorInfo = varMap.get("errorInfo");
		if(userBean == null){
			userBean = new UserBean();
			userBean.setUserType("2");
		}
		if(fileName != null && !fileName.equals("")){
			userBean.setImage("files/"+CCPContants.getCurrUserId()+"/"+fileName);
		}
		if(errorInfo != null && !errorInfo.equals("")){
			showMsg("image", errorInfo);
			userBean.setImage("");
		}
		
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public List<UserBean> getUserList() {
//		if(userList == null || userList.size() == 0)
			getpagedetail();
		return userList;
	}

	public void setUserList(List<UserBean> userList) {
		this.userList = userList;
	}

	public List<String> getSpecialtyList() {
		if(specialtyList == null)
			specialtyList = new ArrayList<String>();
		return specialtyList;
	}

	public void setSpecialtyList(List<String> specialtyList) {
		this.specialtyList = specialtyList;
	}

	public SelectItem[] getFacultySelectItem() {
		if(facultySelectItem == null){
			List<FacultyBean> list = getFacultyService().getAllFaculty();
			facultySelectItem = new SelectItem[list.size()];
			for (int i = 0; i < list.size(); i++) {
				facultySelectItem[i] = new SelectItem(""+list.get(i).getId() , list.get(i).getFacultyName());
			}
		}
		return facultySelectItem;
	}

	public void setFacultySelectItem(SelectItem[] facultySelectItem) {
		this.facultySelectItem = facultySelectItem;
	}

	public SelectItem[] getSpecialtySelectItem() {
		if(specialtySelectItem == null)
			specialtySelectItem = new SelectItem[0];
		return specialtySelectItem;
	}

	public void setSpecialtySelectItem(SelectItem[] specialtySelectItem) {
		this.specialtySelectItem = specialtySelectItem;
	}

	public List<String> getSpecialtyListBak() {
		return specialtyListBak;
	}

	public void setSpecialtyListBak(List<String> specialtyListBak) {
		this.specialtyListBak = specialtyListBak;
	}

	public String getFacultyIDBack() {
		return facultyIDBack;
	}

	public void setFacultyIDBack(String facultyIDBack) {
		this.facultyIDBack = facultyIDBack;
	}

	public String getSearchUserType() {
		return searchUserType;
	}

	public void setSearchUserType(String searchUserType) {
		this.searchUserType = searchUserType;
	}
	public String getSearchStatus() {
		return searchStatus;
	}

	public void setSearchStatus(String searchStatus) {
		this.searchStatus = searchStatus;
	}

	public String getNumber() {
		return number;
	}

	public void setNumber(String number) {
		this.number = number;
	}

	public String getSearchUserName() {
		return searchUserName;
	}

	public void setSearchUserName(String searchUserName) {
		this.searchUserName = searchUserName;
	}

	public String getSearchFacultyId() {
		return searchFacultyId;
	}

	public void setSearchFacultyId(String searchFacultyId) {
		this.searchFacultyId = searchFacultyId;
	}

	public String getSearchSpecialtyId() {
		return searchSpecialtyId;
	}

	public void setSearchSpecialtyId(String searchSpecialtyId) {
		this.searchSpecialtyId = searchSpecialtyId;
	}

	public SelectItem[] getPositionalSelectItem() {
		if(positionalSelectItem == null){
//			positionalSelectItem = new SelectItem[3];
//			positionalSelectItem[0] =   new SelectItem(""+Contants.POSITIONAL_LECTURE , getMessages("user_page_label_positional_lec"));
//			positionalSelectItem[1] =   new SelectItem(""+Contants.POSITIONAL_A_PROFESSOR , getMessages("user_page_label_positional_a_pro"));
//			positionalSelectItem[2] =   new SelectItem(""+Contants.POSITIONAL_PROFESSOR , getMessages("user_page_label_positional_pro"));
			
			List list = getResourseService().pageQueryResourse(Contants.DATA_DICTIONARY_TEACHER_TITLE_TYPE);
			positionalSelectItem = new SelectItem[list.size()];
			for (int i = 0; i < list.size(); i++) {
				ResourseBean bean = (ResourseBean) list.get(i);
				positionalSelectItem[i] =   new SelectItem(""+ bean.getId(), bean.getName());
			}
		}
		return positionalSelectItem;
	}

	public void setPositionalSelectItem(SelectItem[] positionalSelectItem) {
		this.positionalSelectItem = positionalSelectItem;
	}

	public SelectItem[] getTeachGroupSelectItem() {
		if(teachGroupSelectItem == null)
			teachGroupSelectItem = new SelectItem[0];
		return teachGroupSelectItem;
	}

	public void setTeachGroupSelectItem(SelectItem[] teachGroupSelectItem) {
		this.teachGroupSelectItem = teachGroupSelectItem;
	}

	public List<String> getTeachGropList() {
		return teachGropList;
	}

	public void setTeachGropList(List<String> teachGropList) {
		this.teachGropList = teachGropList;
	}

	public SelectItem[] getTeacherTypeSelectItem() {
		if(teacherTypeSelectItem == null){
			List list = getResourseService().pageQueryResourse(Contants.DATA_DICTIONARY_TEACHER_TYPE);
			teacherTypeSelectItem = new SelectItem[list.size()];
			for (int i = 0; i < list.size(); i++) {
				ResourseBean bean = (ResourseBean) list.get(i);
				teacherTypeSelectItem[i] =   new SelectItem( ""+bean.getId(), bean.getName());
			}
		}
		return teacherTypeSelectItem;
	}

	public void setTeacherTypeSelectItem(SelectItem[] teacherTypeSelectItem) {
		this.teacherTypeSelectItem = teacherTypeSelectItem;
	}
	
}
